package com.suning.sawp.service.impl.companymem;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import com.google.common.base.Charsets;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.suning.nsfbus.logistics.dto.RegionInfoDto;
import com.suning.nsfbus.logistics.dto.RegionInfoListDto;
import com.suning.nsfbus.logistics.service.RegionInfoRsfService;
import com.suning.rsc.dto.responsedto.MbfResponse;
import com.suning.rsc.httpservice.annotation.EsbEIHttpWired;
import com.suning.rsc.utils.XStreamUtil;
import com.suning.rsf.consumer.ServiceLocator;
import com.suning.sawp.constants.ConfigConstants;
import com.suning.sawp.constants.ErrorCodeConstants;
import com.suning.sawp.dto.common.ReturnMsg;
import com.suning.sawp.dto.companymem.AdvanceBaseInfo;
import com.suning.sawp.dto.companymem.AdvanceInfo;
import com.suning.sawp.dto.companymem.CompanyMemBaseInfo;
import com.suning.sawp.dto.companymem.CompanyMemRecordInfo;
import com.suning.sawp.dto.companymem.IdentityInfo;
import com.suning.sawp.dto.companymem.MdmCityInfoDto;
import com.suning.sawp.dto.companymem.QueryRecordDetailResult;
import com.suning.sawp.dto.esb.AccountAlias;
import com.suning.sawp.dto.esb.CheckCompanyNameBody;
import com.suning.sawp.dto.esb.CheckCompanyNameReq;
import com.suning.sawp.dto.esb.CheckEmailBody;
import com.suning.sawp.dto.esb.CheckEmailReq;
import com.suning.sawp.dto.esb.ContactPointDj;
import com.suning.sawp.dto.esb.IndividualInfoBody;
import com.suning.sawp.dto.esb.IndividualInfoReq;
import com.suning.sawp.dto.esb.OaApproveFlowReq;
import com.suning.sawp.dto.esb.OaApproveFlowResp;
import com.suning.sawp.dto.esb.OrgRegistrationDj;
import com.suning.sawp.dto.esb.OrganizationBaseDj;
import com.suning.sawp.dto.esb.OrganizationInfoDj;
import com.suning.sawp.dto.esb.QueryCompanyDetailReq;
import com.suning.sawp.dto.esb.QueryCompanyResp;
import com.suning.sawp.dto.esb.QueryCompanySumBody;
import com.suning.sawp.dto.esb.QueryCompanySumReq;
import com.suning.sawp.dto.mainpush.StoreManDto;
import com.suning.sawp.intf.companymem.CompanyMemService;
import com.suning.sawp.intf.esb.B2CAccountEsbService;
import com.suning.sawp.intf.esb.CompanyMemInfoEsbService;
import com.suning.sawp.intf.esb.MemberQueryService;
import com.suning.sawp.po.companymem.MdmCity;
import com.suning.sawp.service.impl.dao.CompanyMemDaoService;
import com.suning.sawp.service.util.AESUtils;
import com.suning.sawp.service.util.DateUtils;
import com.suning.sawp.service.util.MD5Util;
import com.suning.sawp.service.util.XmlUtils;
import com.suning.srs.rsfservice.dto.RegResult;
import com.suning.srs.rsfservice.dto.create2linecompanyaccount.CrtOnlineAndOfflineCompanyAccountParam;
import com.suning.srs.rsfservice.dto.create2linecompanyaccount.CrtOnlineAndOfflineCompanyContactPoint;
import com.suning.srs.rsfservice.dto.create2linecompanyaccount.CrtOnlineAndOfflineCompanyIndividualInfo;
import com.suning.srs.rsfservice.dto.create2linecompanyaccount.CrtOnlineAndOfflineCompanyOrganizationBase;
import com.suning.srs.rsfservice.dto.create2linecompanyaccount.CrtOnlineAndOfflineCompanyOrganizationContactPoint;
import com.suning.srs.rsfservice.dto.create2linecompanyaccount.CrtOnlineAndOfflineCompanyOrganizationInfo;
import com.suning.srs.rsfservice.dto.create2linecompanyaccount.CrtOnlineAndOfflineCompanyOrganizationRegistration;
import com.suning.srs.rsfservice.dto.create2linecompanyaccount.CrtOnlineAndOfflineCompanyRegistration;
import com.suning.srs.rsfservice.service.UserRegisterService;

/**
 * 企业会员实现类
 *
 * @author 15050769
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class CompanyMemServiceImpl implements CompanyMemService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CompanyMemServiceImpl.class);

    private static String EXIST_FLAG = "100000000010";

    private static final String ESB_SUCCESS_STATUS = "COMPLETE";

    private static final String OA_SUCCESS = "S";

    // A11:营业执照副本,B11:税务登记证副本,D11:一般纳税人证书：
    private static final String A11 = "A11";

    private static final String B11 = "B11";

    private static final String D11 = "D11";

    private CompanyMemInfoEsbService companyMemInfoEsbService;

    private B2CAccountEsbService b2CAccountEsbService;

    private MemberQueryService memberQueryService;

    private RegionInfoRsfService regionInfoRsfService = ServiceLocator.getService(RegionInfoRsfService.class, null);

    private UserRegisterService userRegisterService = ServiceLocator.getService(UserRegisterService.class, null);

    @Resource
    CompanyMemDaoService companyMemDaoService;

    private static Map<String, String> esbStatusMap = new HashMap<String, String>();

    private static Map<String, String> failCodeMap = new HashMap<String, String>();

    private static Map<String, String> advanceFailCodeMap = new HashMap<String, String>();

    private static Map<String, String> subFailCodeMap = new HashMap<String, String>();

    @Value("#{settingConfig[cm_kafkaZkServer]}")
    String kafkaZkServer;

    @Value("#{settingConfig[cm_topic]}")
    String topic;

    @Value("#{settingConfig[uimg_head_host]}")
    String urlHeader;

    @Override
    public ReturnMsg<Boolean> checkCompanyNameExists(String companyName) {

        ReturnMsg<Boolean> returnMsg = new ReturnMsg<Boolean>();
        LOGGER.info(" checkCompanyNameExists companyName:" + companyName);

        if (StringUtils.isBlank(companyName)) {
            LOGGER.error(" checkCompanyNameExists companyName is blank companyName:" + companyName);
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return returnMsg;
        }

        CheckCompanyNameReq req = new CheckCompanyNameReq();
        CheckCompanyNameBody body = new CheckCompanyNameBody();
        body.setOrgPartyName(companyName);
        req.setBody(body);
        MbfResponse mbfResponse = null;
        try {
            mbfResponse = companyMemInfoEsbService.checkCompanyNameExists(req);
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error("checkCompanyNameExists ESB error," + req, e);
            return returnMsg;
        }

        if (mbfResponse != null && mbfResponse.getOutput() != null) {
            Document doc;
            try {
                doc = XmlUtils.getW3CDom(mbfResponse.toString());
                LOGGER.info(" checkCompanyNameExists mbfResponse:" + mbfResponse);
                // 已存在
                if (ESB_SUCCESS_STATUS.equals(mbfResponse.getOutput().getMbfHeader().getServiceResponse().getStatus())) {
                    if (EXIST_FLAG.equals(XmlUtils.getValueByXpath(doc, "/MbfService/output1/body/orgNameExistFlag"))) {
                        returnMsg.setData(new Boolean(true));
                    } else {
                        returnMsg.setData(new Boolean(false));
                    }
                } else {
                    returnMsg.setError(ErrorCodeConstants.ERR_0045);
                    LOGGER.error(" checkCompanyNameExists ,fail");
                }
            } catch (Exception e) {
                LOGGER.error(" checkCompanyNameExists:" + companyName, e);
                returnMsg.setError(ErrorCodeConstants.ERR_0045);
            }
        } else {
            LOGGER.error("checkCompanyNameExists,companyName:{}", companyName);
            returnMsg.setError(ErrorCodeConstants.ERR_0045);
        }

        return returnMsg;

    }

    @Override
    public ReturnMsg<Boolean> checkEmail(String email) {
        ReturnMsg<Boolean> returnMsg = new ReturnMsg<Boolean>();
        LOGGER.info(" checkEmail email:" + email);

        if (StringUtils.isBlank(email)) {
            LOGGER.error(" checkEmail email is blank email:" + email);
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return returnMsg;
        }

        CheckEmailReq req = new CheckEmailReq();
        CheckEmailBody body = new CheckEmailBody();
        body.setAliasName(email);
        req.setBody(body);
        MbfResponse mbfResponse = null;
        try {
            mbfResponse = b2CAccountEsbService.checkEmail(req);
        } catch (Exception e) {
            LOGGER.error("checkEmail ESB error," + req, e);
            returnMsg.setError(ErrorCodeConstants.ERR_0045);
            return returnMsg;
        }
        LOGGER.info(" checkEmail mbfResponse:" + mbfResponse);
        if (mbfResponse != null && mbfResponse.getOutput() != null) {
            try {
                if (ESB_SUCCESS_STATUS.equals(mbfResponse.getOutput().getMbfHeader().getServiceResponse().getStatus())) {
                    returnMsg.setData(new Boolean(true));
                } else {
                    LOGGER.info(" checkEmail,fail :" + mbfResponse);
                    returnMsg.setData(new Boolean(false));
                }
            } catch (Exception e) {
                returnMsg.setError(ErrorCodeConstants.ERR_0045);
                LOGGER.error(" checkEmail:" + email, e);
            }
        } else {
            returnMsg.setError(ErrorCodeConstants.ERR_0045);
            LOGGER.error("checkEmail,email:{}", email);
        }
        return returnMsg;
    }

    @Override
    public int[] saveMdmCityInfo(List<MdmCity> tmpList) {
        return null;
    }

    @Override
    public ReturnMsg<List<MdmCityInfoDto>> queryCityInfo(String zoneId, String zoneLevel) {
        ReturnMsg<List<MdmCityInfoDto>> returnMsg = new ReturnMsg<List<MdmCityInfoDto>>();
        LOGGER.info(" queryCityInfo zoneId:{},zoneLevel:{}", zoneId, zoneLevel);
        List<MdmCityInfoDto> result = null;
        try {
            RegionInfoListDto regionInfoListDto = regionInfoRsfService.queryRegionListByParentCode(zoneId, zoneLevel);
            if (regionInfoListDto != null && CollectionUtils.isNotEmpty(regionInfoListDto.getRegionInfoDtoList())) {
                result = Lists.newArrayList(Lists.transform(regionInfoListDto.getRegionInfoDtoList(),
                        new Function<RegionInfoDto, MdmCityInfoDto>() {
                            @Override
                            public MdmCityInfoDto apply(RegionInfoDto input) {
                                MdmCityInfoDto detail = new MdmCityInfoDto();
                                if (input != null) {
                                    detail.setZoneId(input.getRegionalCode());
                                    detail.setZoneLevel(input.getRegionalLevel());
                                    detail.setZoneName(input.getRegionalName());
                                    detail.setParId(input.getParentRegionalCode());
                                }
                                return detail;
                            }
                        }));

            }
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
            LOGGER.error(" queryCityInfo has exception ", e);
            return returnMsg;
        }

        if (result == null) {
            LOGGER.error(" queryCityInfo result is null zoneId:{},zoneLevel:{}", zoneId, zoneLevel);
            returnMsg.setError(ErrorCodeConstants.ERR_0002);
        }

        returnMsg.setData(result);
        return returnMsg;
    }

    @Override
    public ReturnMsg<String> submitBaseInfo(CompanyMemBaseInfo companyMemBaseInfo, StoreManDto storeManDto) {

        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        if (companyMemBaseInfo == null || storeManDto == null) {
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return returnMsg;
        }
        LOGGER.info("submitBaseInfo companyMemBaseInfo:{}", companyMemBaseInfo);
        try {
            CrtOnlineAndOfflineCompanyAccountParam param = new CrtOnlineAndOfflineCompanyAccountParam();

            param.setSourceChannel(storeManDto.getStoreCode());
            param.setSourceByEmployee(storeManDto.getStaffId());
            param.setEcoType("140000000020");
            param.setBranch(storeManDto.getBranchCode());
            param.setStore(storeManDto.getStoreCode());
            param.setAliasName(companyMemBaseInfo.getEmail());
            param.setAliasType("138000000020");// CodeString邮箱(Email)
            param.setAliasVerifyStat("125000000010");// CodeString未验证
            if ("0".equals(companyMemBaseInfo.getChannel())) {
                param.setAccountCreatedChannel("208000201021");// CodeString PC-Windows IOS
            } else {
                param.setAccountCreatedChannel("208000202021");// CodeString PC-Windows 安卓
            }

            CrtOnlineAndOfflineCompanyIndividualInfo individualInfo = new CrtOnlineAndOfflineCompanyIndividualInfo();

            CrtOnlineAndOfflineCompanyRegistration individualInfo_registration = new CrtOnlineAndOfflineCompanyRegistration();
            individualInfo_registration.setPartyName(companyMemBaseInfo.getCustName());
            individualInfo.setRegistration(individualInfo_registration);

            List<CrtOnlineAndOfflineCompanyContactPoint> individualInfo_contactPointList = new ArrayList<CrtOnlineAndOfflineCompanyContactPoint>();
            CrtOnlineAndOfflineCompanyContactPoint individualInfo_contactPoint = new CrtOnlineAndOfflineCompanyContactPoint();
            individualInfo_contactPoint.setCntctPointType("143000000010");// CodeString家庭地址
            individualInfo_contactPoint.setMobileNumMain(companyMemBaseInfo.getCustMobile());
            individualInfo_contactPoint.setPreferFlag("100000000010");// CodeString是
            individualInfo_contactPointList.add(individualInfo_contactPoint);
            individualInfo.setContactPointList(individualInfo_contactPointList);

            // param
            param.setIndividualInfo(individualInfo);

            CrtOnlineAndOfflineCompanyOrganizationInfo organizationInfo = new CrtOnlineAndOfflineCompanyOrganizationInfo();

            CrtOnlineAndOfflineCompanyOrganizationRegistration organizationInfo_registration = new CrtOnlineAndOfflineCompanyOrganizationRegistration();
            organizationInfo_registration.setPartyName(companyMemBaseInfo.getCompanyName());
            organizationInfo.setRegistration(organizationInfo_registration);

            CrtOnlineAndOfflineCompanyOrganizationBase organizationInfo_organizationBase = new CrtOnlineAndOfflineCompanyOrganizationBase();
            organizationInfo.setOrganizationBase(organizationInfo_organizationBase);

            List<CrtOnlineAndOfflineCompanyOrganizationContactPoint> organizationInfo_contactPointList = new ArrayList<CrtOnlineAndOfflineCompanyOrganizationContactPoint>();
            CrtOnlineAndOfflineCompanyOrganizationContactPoint organizationInfo_contactPoint = new CrtOnlineAndOfflineCompanyOrganizationContactPoint();
            organizationInfo_contactPoint.setCntctPointType("143000000060");// CodeString单位注册地址
            organizationInfo_contactPoint.setState(companyMemBaseInfo.getProvinceId());
            organizationInfo_contactPoint.setCity(companyMemBaseInfo.getCityId());
            organizationInfo_contactPoint.setTown(companyMemBaseInfo.getAreaId());
            organizationInfo_contactPoint.setStreet(companyMemBaseInfo.getStreetId());
            organizationInfo_contactPoint.setAddress(companyMemBaseInfo.getOfficeAddress());
            organizationInfo_contactPointList.add(organizationInfo_contactPoint);
            organizationInfo.setContactPointList(organizationInfo_contactPointList);

            // param
            param.setOrganizationInfo(organizationInfo);

            RegResult submitResult = userRegisterService.createOnlineAndOfflineCompanyAccount(param);
            LOGGER.info("submitBaseInfo submitResult:{}", submitResult);
            // 失败
            if (submitResult == null) {
                LOGGER.error("submitBaseInfo createOnlineAndOfflineCompanyAccount fail submitResult:", submitResult);
                returnMsg.setError(ErrorCodeConstants.ERR_0042);
                return returnMsg;
            } else if (!ESB_SUCCESS_STATUS.equals(submitResult.getCode())
                    || StringUtils.isBlank(submitResult.getCustNum())) {
                LOGGER.error("submitBaseInfo createOnlineAndOfflineCompanyAccount fail submitResult : " + submitResult);
                returnMsg.setError(submitResult.getCode(), geBaseFailMsg(submitResult.getCode()));
            } else {
                // 保存入库
                companyMemBaseInfo.setCustNum(submitResult.getCustNum());
                companyMemBaseInfo.setCustCardNum(submitResult.getCardNo());
                boolean daoResult = companyMemDaoService.submitBaseInfo(companyMemBaseInfo, storeManDto);
                if (!daoResult) {
                    LOGGER.error("companyMemDaoService_submitBaseInfo_fail storeManDto:{},custnum:{}", storeManDto,
                            submitResult.getCustNum());
                    returnMsg.setError(ErrorCodeConstants.ERR_0046);
                } else {
                    returnMsg.setData(AESUtils.encrypt(submitResult.getCustNum(), ConfigConstants.AES_KEY));
                }
            }
        } catch (Exception e) {
            returnMsg.setError(ErrorCodeConstants.ERR_0042);
            LOGGER.error(" submitBaseInfo has exception ", e);
        }

        return returnMsg;
    }

    @Override
    public ReturnMsg<String> submitIdentityInfo(String businessLicenceId, String businessLicenceUrl, String custNum,
            StoreManDto storeManDto) {

        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        LOGGER.info("submitIdentityInfo businessLicenceId:{},businessLicenceUrl:{},,custNum:{}", businessLicenceId,
                businessLicenceUrl, custNum);

        IndividualInfoReq req = new IndividualInfoReq();
        IndividualInfoBody body = new IndividualInfoBody();
        String custNumParm = AESUtils.decrypt(custNum, ConfigConstants.AES_KEY);
        if (StringUtils.isBlank(custNumParm)) {
            LOGGER.error("submitIdentityInfo custNum  is null");
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return returnMsg;
        }
        body.setCustNum(custNumParm);
        req.setBody(body);

        OrganizationInfoDj organizationInfo = new OrganizationInfoDj();
        body.setOrganizationInfo(organizationInfo);

        OrganizationBaseDj organizationBase = new OrganizationBaseDj();
        organizationBase.setCertNoOther(businessLicenceId);
        organizationBase.setCertTypeOther("131000000170");
        organizationBase.setCustBizLicenceId(MD5Util.getMD5(custNumParm, Charsets.UTF_8.toString()) + "_" + A11);
        organizationBase.setCertValidStat("233000000020");
        organizationInfo.setOrganizationBase(organizationBase);

        req.setBody(body);
        MbfResponse mbfResponse = null;
        try {
            LOGGER.info(" submitIdentityInfo req:" + req);
            mbfResponse = memberQueryService.updateEnterpriseMemberIndividualInfo(req);
        } catch (Exception e) {
            LOGGER.error("submitIdentityInfo ESB error," + req, e);
            returnMsg.setError(ErrorCodeConstants.ERR_0045);
            return returnMsg;
        }

        LOGGER.info(" submitIdentityInfo mbfResponse:" + mbfResponse);
        if (mbfResponse != null && mbfResponse.getOutput() != null && mbfResponse.getOutput().getMbfHeader() != null
                && mbfResponse.getOutput().getMbfHeader().getServiceResponse() != null) {
            try {
                // 如果注册失败
                if (!ESB_SUCCESS_STATUS.equals(mbfResponse.getOutput().getMbfHeader().getServiceResponse().getStatus())) {
                    LOGGER.error(" submitIdentityInfo ,fail" + mbfResponse);
                    returnMsg.setError(mbfResponse.getOutput().getMbfHeader().getServiceResponse().getCode(),
                            mbfResponse.getOutput().getMbfHeader().getServiceResponse().getDesc());
                } else {
                    // 更新记录时间
                    companyMemDaoService.updateRecord(custNumParm);
                    // 提交OA申请
                    OaApproveFlowReq oaApproveFlowReq = new OaApproveFlowReq();
                    oaApproveFlowReq.setCustNum(AESUtils.decrypt(custNum, ConfigConstants.AES_KEY));
                    oaApproveFlowReq.setValidateType("100000000010");
                    MbfResponse oaMbfResponse = memberQueryService.syncMemberApproveFlow(oaApproveFlowReq);
                    LOGGER.info(" syncMemberApproveFlow oaMbfResponse:" + oaMbfResponse);
                    if (oaMbfResponse != null && oaMbfResponse.getOutput() != null) {
                        OaApproveFlowResp oaApproveFlowResp = (OaApproveFlowResp) oaMbfResponse.getOutput().getMbfBody(
                                OaApproveFlowResp.class);
                        if (!OA_SUCCESS.equals(oaApproveFlowResp.getResult())) {
                            LOGGER.error(" syncMemberApproveFlow fail : req" + oaApproveFlowReq);
                        }
                    } else {
                        LOGGER.error(" syncMemberApproveFlow ,oaMbfResponse is null : req" + oaApproveFlowReq);
                        returnMsg.setError(ErrorCodeConstants.ERR_0045);
                    }
                }
            } catch (Exception e) {
                LOGGER.error(" submitIdentityInfo req:" + req, e);
                returnMsg.setError(ErrorCodeConstants.ERR_0045);
            }
        } else {
            LOGGER.error(" submitIdentityInfo ,mbfResponse is null : req" + req);
            returnMsg.setError(ErrorCodeConstants.ERR_0045);
        }

        return returnMsg;
    }

    @Override
    public ReturnMsg<String> submitAdvanceInfo(AdvanceBaseInfo advanceBaseInfo) {

        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        LOGGER.info("submitAdvanceInfo businessLicenceId:{},businessLicenceUrl:{},,custNum:{}", advanceBaseInfo);

        if (advanceBaseInfo == null) {
            LOGGER.error("submitAdvanceInfo advanceBaseInfo is null");
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return returnMsg;
        }
        IndividualInfoReq req = new IndividualInfoReq();
        IndividualInfoBody body = new IndividualInfoBody();
        String custNum = AESUtils.decrypt(advanceBaseInfo.getCustNum(), ConfigConstants.AES_KEY);
        if (StringUtils.isBlank(custNum)) {
            LOGGER.error("submitAdvanceInfo custNum  is null");
            returnMsg.setError(ErrorCodeConstants.ERR_0001);
            return returnMsg;
        }
        // 会员编码
        body.setCustNum(custNum);
        req.setBody(body);

        OrganizationInfoDj organizationInfo = new OrganizationInfoDj();
        body.setOrganizationInfo(organizationInfo);

        OrgRegistrationDj registration = new OrgRegistrationDj();
        // 税务登记号
        registration.setCertType("131000000190");
        registration.setCertNo(advanceBaseInfo.getTaxId());
        // 开票单位
        registration.setVatName(advanceBaseInfo.getLicenceName());
        organizationInfo.setRegistration(registration);

        OrganizationBaseDj organizationBase = new OrganizationBaseDj();
        organizationBase.setBankName(advanceBaseInfo.getBankName());
        organizationBase.setBankDepositAcnt(advanceBaseInfo.getBankAcount());
        organizationBase.setTaxRegCertId(MD5Util.getMD5(custNum, Charsets.UTF_8.toString()) + "_" + B11);
        organizationBase.setTaxpayerCertId(MD5Util.getMD5(custNum, Charsets.UTF_8.toString()) + "_" + D11);
        organizationBase.setVatQlfctStat("234000000020");
        organizationInfo.setOrganizationBase(organizationBase);

        List<ContactPointDj> contactPointList = new ArrayList<ContactPointDj>();
        ContactPointDj contactPointDj = new ContactPointDj();
        contactPointDj.setAddress(advanceBaseInfo.getRegisterAddress());
        contactPointDj.setState(advanceBaseInfo.getProvinceId());
        contactPointDj.setCity(advanceBaseInfo.getCityId());
        contactPointDj.setTown(advanceBaseInfo.getAreaId());
        // 如果区号为空则联系方式为手机号码 否则为固话
        if (StringUtils.isBlank(advanceBaseInfo.getAreaCode())) {
            contactPointDj.setTeleNumMain(advanceBaseInfo.getRegisterPhoneNum());
        } else {
            contactPointDj.setTeleAreaCdeMain(advanceBaseInfo.getAreaCode());
            contactPointDj.setTeleNumMain(advanceBaseInfo.getRegisterPhoneNum());
        }
        contactPointDj.setCntctPointType("143000000020");
        contactPointList.add(contactPointDj);
        organizationInfo.setContactPointList(contactPointList);

        req.setBody(body);
        MbfResponse mbfResponse = null;
        try {
            LOGGER.info(" submitAdvanceInfo req:" + req);
            mbfResponse = memberQueryService.updateEnterpriseMemberIndividualInfo(req);
        } catch (Exception e) {
            LOGGER.error("submitAdvanceInfo ESB error," + req, e);
            returnMsg.setError(ErrorCodeConstants.ERR_0045);
        }

        LOGGER.info(" submitAdvanceInfo mbfResponse:" + mbfResponse);
        if (mbfResponse != null && mbfResponse.getOutput() != null && mbfResponse.getOutput().getMbfHeader() != null
                && mbfResponse.getOutput().getMbfHeader().getServiceResponse() != null) {
            try {
                // 如果注册成功
                if (!ESB_SUCCESS_STATUS.equals(mbfResponse.getOutput().getMbfHeader().getServiceResponse().getStatus())) {
                    LOGGER.error(" submitAdvanceInfo ,fail" + mbfResponse);
                    returnMsg.setError(mbfResponse.getOutput().getMbfHeader().getServiceResponse().getCode(),
                            mbfResponse.getOutput().getMbfHeader().getServiceResponse().getDesc());
                } else {
                    // 更新记录时间
                    companyMemDaoService.updateRecord(custNum);
                    // 提交OA申请
                    OaApproveFlowReq oaApproveFlowReq = new OaApproveFlowReq();
                    oaApproveFlowReq
                            .setCustNum(AESUtils.decrypt(advanceBaseInfo.getCustNum(), ConfigConstants.AES_KEY));
                    oaApproveFlowReq.setValidateType("100000000020");
                    MbfResponse oaMbfResponse = memberQueryService.syncMemberApproveFlow(oaApproveFlowReq);

                    LOGGER.info(" syncMemberApproveFlow oaMbfResponse:" + oaMbfResponse);
                    if (oaMbfResponse != null && oaMbfResponse.getOutput() != null) {
                        OaApproveFlowResp oaApproveFlowResp = (OaApproveFlowResp) oaMbfResponse.getOutput().getMbfBody(
                                OaApproveFlowResp.class);
                        if (!OA_SUCCESS.equals(oaApproveFlowResp.getResult())) {
                            LOGGER.error(" syncMemberApproveFlow fail : req" + oaApproveFlowReq);
                        }
                    } else {
                        LOGGER.error(" syncMemberApproveFlow ,oaMbfResponse is null : req" + oaApproveFlowReq);
                        returnMsg.setError(ErrorCodeConstants.ERR_0045);
                    }
                }
            } catch (Exception e) {
                LOGGER.error(" submitAdvanceInfo req:" + req, e);
                returnMsg.setError(ErrorCodeConstants.ERR_0045);
            }
        } else {
            LOGGER.error(" submitAdvanceInfo ,mbfResponse is null : req" + req);
            returnMsg.setError(ErrorCodeConstants.ERR_0045);
        }
        return returnMsg;
    }

    @Override
    public ReturnMsg<List<CompanyMemRecordInfo>> queryRecordByParm(String queryDate, String queryParm, int index,
            int size, StoreManDto storeManDto) {

        ReturnMsg<List<CompanyMemRecordInfo>> returnMsg = new ReturnMsg<List<CompanyMemRecordInfo>>();
        LOGGER.info("queryRecordByParm queryDate:{},queryParm:{},index:{},size:{}", queryDate, queryParm, index, size);
        try {
            List<CompanyMemRecordInfo> resultList = companyMemDaoService.queryRecordByParm(queryDate, queryParm, index,
                    size, storeManDto);

            if (resultList == null) {
                LOGGER.error(" queryRecordByParm resultList is null");
                returnMsg.setError(ErrorCodeConstants.ERR_0046);
                return returnMsg;
            } else {
                for (CompanyMemRecordInfo item : resultList) {
                    if (item == null || StringUtils.isBlank(item.getCustNum())) {
                        continue;
                    }

                    QueryCompanySumReq queryCompanySumReq = new QueryCompanySumReq();
                    QueryCompanySumBody body = queryCompanySumReq.getBody();
                    body.setCustNum(item.getCustNum());
                    MbfResponse mbfResponse = null;
                    try {
                        mbfResponse = companyMemInfoEsbService.queryCompanyMemSumary(queryCompanySumReq);
                    } catch (Exception e) {
                        returnMsg.setError(ErrorCodeConstants.ERR_0002);
                        LOGGER.error("queryCompanyMemSumary ESB error," + queryCompanySumReq, e);
                        return returnMsg;
                    }

                    LOGGER.info(" queryCompanyMemSumary mbfResponse:" + mbfResponse);
                    if (mbfResponse != null && mbfResponse.getOutput() != null
                            && mbfResponse.getOutput().getMbfHeader() != null
                            && mbfResponse.getOutput().getMbfHeader().getServiceResponse() != null) {
                        Document doc;
                        try {
                            doc = XmlUtils.getW3CDom(mbfResponse.toString());
                            if (ESB_SUCCESS_STATUS.equals(mbfResponse.getOutput().getMbfHeader().getServiceResponse()
                                    .getStatus())) {

                                String identityResult = XmlUtils.getValueByXpath(doc,
                                        "/MbfService/output1/body/certValidStat");
                                item.setApprovalStatus(getRegisterStatus(identityResult, "0"));
                            } else {
                                returnMsg.setError(ErrorCodeConstants.ERR_0045);
                                LOGGER.error(" queryCompanyMemSumary ,fail");
                            }
                        } catch (Exception e) {
                            LOGGER.error(" queryCompanyMemSumary :" + item.getCustNum(), e);
                            returnMsg.setError(ErrorCodeConstants.ERR_0045);
                        }
                    } else {
                        LOGGER.error("queryCompanyMemSumary,custnum :{}", item.getCustNum());
                        returnMsg.setError(ErrorCodeConstants.ERR_0045);
                    }
                    item.setCustNum(AESUtils.encrypt(item.getCustNum(), ConfigConstants.AES_KEY));
                    item.setCustMobile(StringUtils.isBlank(item.getCustMobile()) ? "" : AESUtils.encrypt(
                            item.getCustMobile(), ConfigConstants.AES_KEY));
                }
                returnMsg.setData(resultList);
            }
        } catch (Exception e) {
            LOGGER.error(" queryRecordByParm exception", e);
            returnMsg.setError(ErrorCodeConstants.ERR_0046);
        }
        return returnMsg;
    }

    @Override
    public ReturnMsg<String> deleteRecord(String recordId) {

        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        LOGGER.info("deleteRecord recordId:{}", recordId);
        try {
            int deleteResult = companyMemDaoService.deleteRecord(recordId);
            if (deleteResult != 1) {
                LOGGER.error("deleteRecord dao error,deleteResult :" + deleteResult);
            }
        } catch (Exception e) {
            LOGGER.error("deleteRecord dao exception,", e);
            returnMsg.setError(ErrorCodeConstants.ERR_0045);
            return returnMsg;
        }
        return returnMsg;
    }

    @Override
    public ReturnMsg<QueryRecordDetailResult> quertRecordDetail(String recordId, String custNum) {

        ReturnMsg<QueryRecordDetailResult> returnMsg = new ReturnMsg<QueryRecordDetailResult>();
        LOGGER.info("quertRecordDetail recordId:{}", recordId);
        try {
            String custNumParm = AESUtils.decrypt(custNum, ConfigConstants.AES_KEY);
            if (StringUtils.isBlank(custNumParm)) {
                returnMsg.setError(ErrorCodeConstants.ERR_0001);
                LOGGER.error("quertRecordDetail custNum is null ,custNum:" + custNum);
                return returnMsg;
            }

            QueryCompanyDetailReq queryCompanyDetailReq = new QueryCompanyDetailReq();
            QueryCompanySumBody body = queryCompanyDetailReq.getBody();
            body.setCustNum(custNumParm);
            MbfResponse mbfResponse = null;
            try {
                mbfResponse = companyMemInfoEsbService.queryCompanyMemDetail(queryCompanyDetailReq);
            } catch (Exception e) {
                returnMsg.setError(ErrorCodeConstants.ERR_0002);
                LOGGER.error("quertRecordDetail ESB error," + queryCompanyDetailReq, e);
                return returnMsg;
            }
            QueryRecordDetailResult queryRecordDetailResult;
            LOGGER.info(" quertRecordDetail mbfResponse:" + mbfResponse);
            if (mbfResponse != null && mbfResponse.getOutput() != null) {
                String xml = mbfResponse.getOutput().getMbfBodyXml();
                if (StringUtils.isNotBlank(xml)) {
                    int beginIndex = xml.indexOf("<body>");
                    int endIndex = xml.indexOf("</body>");
                    String bodyXml = "";
                    if (beginIndex != -1 && endIndex != -1) {
                        bodyXml = xml.substring(beginIndex, endIndex + "</body>".length());
                    }
                    QueryCompanyResp queryResult = (QueryCompanyResp) XStreamUtil.xmlToObject(bodyXml,
                            QueryCompanyResp.class);
                    queryRecordDetailResult = tranRecordDetail(queryResult);
                    returnMsg.setData(queryRecordDetailResult);
                } else {
                    LOGGER.error("quertRecordDetail,MbfBodyXm is empty ");
                    returnMsg.setError(ErrorCodeConstants.ERR_0045);
                }
            } else {
                LOGGER.error("quertRecordDetail,custnum :{}", custNum);
                returnMsg.setError(ErrorCodeConstants.ERR_0045);
            }

        } catch (Exception e) {
            LOGGER.error(" queryRecordByParm exception", e);
            returnMsg.setError(ErrorCodeConstants.ERR_0046);
        }
        return returnMsg;

    }

    @Override
    public ReturnMsg<String> submitSensitiveVisitRecord(String mId, String mobileNum, String staffId, String requestIp) {
        ReturnMsg<String> returnMsg = new ReturnMsg<String>();
        KafkaProducer KafkaProducer = new KafkaProducer(kafkaZkServer, topic);
        JSONObject jb = new JSONObject();
        jb.put("employee_id", staffId);
        jb.put("sys_name", "SNSAWP");
        jb.put("ip_addr", requestIp);
        jb.put("mac_addr", AESUtils.decrypt(mId, ConfigConstants.AES_KEY));

        jb.put("visit_page", "企业会员拨号");
        jb.put("visit_time", DateUtils.getDateStrByFormat(new Date(), DateUtils.ACCURATE_MINUTES_PATTERN_2));
        jb.put("rece_tel", "Y");
        try {
            KafkaProducer.produce(jb.toString(), "SNSAWP_CM");
        } catch (Exception e) {
            LOGGER.error("submitSensitiveVisitRecord exception " + jb.toString(), e);
            returnMsg.setError(ErrorCodeConstants.ERR_0001, "");
        }
        return returnMsg;
    }

    private String getImgUrlByCustInfo(String custInfo) {
        if (StringUtils.isBlank(custInfo)) {
            return "";
        } else {
            return urlHeader + String.format("/uimg/srs/certificates/%s.jpg", custInfo);
        }
    }

    private QueryRecordDetailResult tranRecordDetail(QueryCompanyResp queryResult) {
        List<AccountAlias> accountAliasList = queryResult.getAccountAliasList();
        List<ContactPointDj> contactPointDjList = queryResult.getContactPointList();

        QueryRecordDetailResult queryRecordDetailResult = new QueryRecordDetailResult();
        IdentityInfo identityInfo = queryRecordDetailResult.getIdentityInfo();
        identityInfo.setBusinessLicenceId(StringUtils.isBlank(queryResult.getCertNo2()) ? "" : AESUtils.encrypt(
                queryResult.getCertNo2(), ConfigConstants.AES_KEY));
        identityInfo.setBusinessLicenceUrl(getImgUrlByCustInfo(queryResult.getCustBizLicenceId()));
        AdvanceInfo advanceInfo = queryRecordDetailResult.getAdvanceInfo();
        if (CollectionUtils.isNotEmpty(contactPointDjList)) {
            for (ContactPointDj item : contactPointDjList) {
                if (item == null) {
                    continue;
                }
                // 1/2/3/4/5 国家/省/市/区/镇
                // 143000000020 单位注册地址
                // 143000000060 公司办公地址
                // 注册地址
                if ("143000000020".equals(item.getCntctPointType())) {
                    advanceInfo.setCityId(item.getCity());
                    advanceInfo.setCityName(getAreaName(item.getCity(), "3"));
                    advanceInfo.setProvinceId(item.getState());
                    advanceInfo.setProvinceName(getAreaName(item.getState(), "2"));
                    advanceInfo.setAreaId(item.getTown());
                    advanceInfo.setAreaName(getAreaName(item.getTown(), "4"));
                    advanceInfo.setRegisterAddress(item.getAddress());
                    if (StringUtils.isNotBlank(item.getTeleNumMain())) {
                        advanceInfo.setRegisterPhoneNum(StringUtils.isBlank(item.getTeleNumMain()) ? "" : AESUtils
                                .encrypt(item.getTeleNumMain(), ConfigConstants.AES_KEY));
                        advanceInfo.setRegisterAreaCode(item.getTeleAreaCdeMain());
                    }
                }
                // 办公地址
                if ("143000000060".equals(item.getCntctPointType())) {
                    queryRecordDetailResult.setOfficeAddress(getAreaName(item.getState(), "2")
                            + getAreaName(item.getCity(), "3") + getAreaName(item.getTown(), "4") + item.getAddress());
                }
            }
        }
        advanceInfo.setBankAcount(StringUtils.isBlank(queryResult.getBankAcnt()) ? "" : AESUtils.encrypt(
                queryResult.getBankAcnt(), ConfigConstants.AES_KEY));
        advanceInfo.setBankName(queryResult.getBankName());

        advanceInfo.setLicenceName(queryResult.getVatName());

        advanceInfo.setTaxId(StringUtils.isBlank(queryResult.getCertNo()) ? "" : AESUtils.encrypt(
                queryResult.getCertNo(), ConfigConstants.AES_KEY));
        advanceInfo.setTaxManUrl(getImgUrlByCustInfo(queryResult.getTaxPayerCertId()));
        advanceInfo.setTaxUrl(getImgUrlByCustInfo(queryResult.getTaxRegCertId()));

        queryRecordDetailResult.setAdvanceApprovalMsg(getAdvanceFailMsg(queryResult.getVatQlfctStatUpdRsn()));
        queryRecordDetailResult.setAdvanceApprovalStatus(getRegisterStatus(queryResult.getVatQlfctStat(), "1"));
        queryRecordDetailResult.setCompanyName(queryResult.getOrgPartyName());

        queryRecordDetailResult.setCustMobile(StringUtils.isBlank(queryResult.getCntctMobileNum()) ? "" : AESUtils
                .encrypt(queryResult.getCntctMobileNum(), ConfigConstants.AES_KEY));
        queryRecordDetailResult.setCustName(queryResult.getCntctPartyName());

        if (accountAliasList != null && accountAliasList.get(0) != null) {
            queryRecordDetailResult.setEmail(StringUtils.isBlank(accountAliasList.get(0).getAliasName()) ? ""
                    : AESUtils.encrypt(accountAliasList.get(0).getAliasName(), ConfigConstants.AES_KEY));
        }
        queryRecordDetailResult.setIdentityApprovalMsg(getIdentityFailMsg(queryResult.getCertValidStatUpdRsn()));
        queryRecordDetailResult.setIdentityApprovalStatus(getRegisterStatus(queryResult.getCertValidStat(), "0"));
        return queryRecordDetailResult;
    }

    private String getAreaName(String code, String level) {
        if (StringUtils.isBlank(code) || StringUtils.isBlank(level)) {
            return "";
        }
        RegionInfoDto regionInfoDto = regionInfoRsfService.queryRegionInfoByRegionalCode(code, level);
        if (regionInfoDto != null) {
            return regionInfoDto.getRegionalName();
        } else {
            return "";
        }
    }

    /**
     * 身份认证状态 233000000000 未输入 233000000010 未认证 233000000020 认证中 233000000030 已认证 233000000040 认证失败 增票资质状态 234000000000
     * 未输入 234000000010 待审核 234000000020 审核中 234000000030 审核失败 234000000040 审核通过 0：未认证；1：认证中；2：认证失败；3认证成功
     * 
     * type 0：身份　1：增票
     */
    private String getRegisterStatus(String esbStatus, String type) {

        if (StringUtils.isBlank(esbStatus) || StringUtils.isBlank(type)) {
            return null;
        }
        if (esbStatusMap.isEmpty()) {
            esbStatusMap.put("233000000000", "0");
            esbStatusMap.put("233000000010", "0");
            esbStatusMap.put("233000000020", "1");
            esbStatusMap.put("233000000030", "3");
            esbStatusMap.put("233000000040", "2");
            esbStatusMap.put("234000000000", "0");
            esbStatusMap.put("234000000010", "0");
            esbStatusMap.put("234000000020", "1");
            esbStatusMap.put("234000000030", "2");
            esbStatusMap.put("234000000040", "3");
        }
        return esbStatusMap.get(esbStatus);
    }

    private String getIdentityFailMsg(String status) {
        if (StringUtils.isBlank(status)) {
            return null;
        }
        if (failCodeMap.isEmpty()) {
            failCodeMap.put("235000000000", "");
            failCodeMap.put("235000000010", "营业执照号与营业执照副本不符");
            failCodeMap.put("235000000020", "营业执照副本未年检");
            failCodeMap.put("235000000030", "营业执照副本未加盖公章");
            failCodeMap.put("235000000040", "资质文件非营业执照副本");
            failCodeMap.put("235000000050", "资质文件非营业执照副本");
            failCodeMap.put("235000000060", "单位名称与资质文件单位名称不一致");
            failCodeMap.put("235000000070", "资质图片拍摄不完整");
            failCodeMap.put("235000000080", "个体单位不同意申请企业用户");
            failCodeMap.put("235099999998", "");
        }
        return failCodeMap.get(status);
    }

    private String geBaseFailMsg(String status) {
        if (StringUtils.isBlank(status)) {
            return null;
        }
        if (subFailCodeMap.isEmpty()) {
            subFailCodeMap.put("ESRS00001", "手机号为空或格式错误");
            subFailCodeMap.put("ESRS00002", "会员编号为空或格式错误");
            subFailCodeMap.put("ESRS00003", "系统异常，请稍后重试");
            subFailCodeMap.put("ESRS00004", "邮箱为不得为空");
            subFailCodeMap.put("ESRS00005", "系统异常，请稍后重试");
            subFailCodeMap.put("ESRS00006", "创建会员账号失败，请重试");
            subFailCodeMap.put("ESRS00007", "验证码校验失败，请重试");
            subFailCodeMap.put("ESRS00008", "您的组织信息中不包含门店，故无法注册双线企业会员哦！");
            subFailCodeMap.put("ESRS00009", "输入的资料有格式不正确哦！");
            subFailCodeMap.put("ESRS00010", "该邮箱已注册会员，请直接购物或更换邮箱");
            subFailCodeMap.put("ESRS00011", "该邮箱已注册会员，请直接购物或更换邮箱");
            subFailCodeMap.put("ESRS00012", "系统异常，请稍后重试");
            subFailCodeMap.put("ESRS00013", "系统异常，请稍后重试");
            subFailCodeMap.put("ESRS00014", "不能基于该会员卡号创建账户");
            subFailCodeMap.put("ESRS00015", "系统异常，请稍后重试");
            subFailCodeMap.put("ESRS00016", "系统异常，请稍后重试");
            subFailCodeMap.put("ESRS00017", "手机号已存在");
            subFailCodeMap.put("ESRS00018", "此会员卡中没有可以用来注册账号的绑定手机号");
            subFailCodeMap.put("ESRS00019", "账号已存在");
            subFailCodeMap.put("ESRS00020", "邮箱有误");
            subFailCodeMap.put("ESRS00999", "您的网络不给力哦，请稍后再试");
            subFailCodeMap.put("E4700A08", "邮箱格式不正确，请更换");
        }
        return subFailCodeMap.get(status);
    }

    private String getAdvanceFailMsg(String status) {
        if (StringUtils.isBlank(status)) {
            return null;
        }
        if (advanceFailCodeMap.isEmpty()) {
            advanceFailCodeMap.put("236000000000", "");
            advanceFailCodeMap.put("236000000010", "资质信息与资质文件不符");
            advanceFailCodeMap.put("236000000020", "营业执照副本未年检");
            advanceFailCodeMap.put("236000000030", "资质文件未加盖公章");
            advanceFailCodeMap.put("236000000040", "上传文件非要求的资质文件");
            advanceFailCodeMap.put("236000000050", "资质文件副本不清晰");
            advanceFailCodeMap.put("236000000060", "营业执照副本不清晰");
            advanceFailCodeMap.put("236000000070", "税务登记证副本不清晰");
            advanceFailCodeMap.put("236000000080", "开户银行许可证副本不清晰");
            advanceFailCodeMap.put("236000000090", "一般纳税人证书副本不清晰");
            advanceFailCodeMap.put("236000000100", "同一公司数量申请超过限额");
            advanceFailCodeMap.put("236000000110", "单位名称与资质文件单位名称不一致");
            advanceFailCodeMap.put("236000000120", "资质文件不清晰");
            advanceFailCodeMap.put("236000000130", "请上传税务登记证或三证合一证件");
            advanceFailCodeMap.put("236000000140", "请上传一般纳税人资格证或税务局认定的资质");
            advanceFailCodeMap.put("236000000150", "请上传个人增票授权委托书");
            advanceFailCodeMap.put("236000000160", "个人增票授权委托书未加盖公章");
            advanceFailCodeMap.put("236000000170", "个人增票授权委托书公章名称与开票名称不一致");
            advanceFailCodeMap.put("236000000180", "资质图片拍摄不完整");
            advanceFailCodeMap.put("236000000190", "旧税号请上传近期开具的增值税专用发票");
            advanceFailCodeMap.put("236000000200", "税号为社会信用代码，请上传三证合一的证照");
            advanceFailCodeMap.put("236000000210", "资质信息与资质文件不符");
            advanceFailCodeMap.put("236000000220", "经营范围不含食品酒水、美妆等，无法开具增票");
            advanceFailCodeMap.put("236000000230", "三/五证合一的营业执照不清晰");
            advanceFailCodeMap.put("236000000240", "所上传的材料未盖章");
            advanceFailCodeMap.put("236000000250", "上传材料的企业主体与入驻的企业主体不一致");
            advanceFailCodeMap.put("236000000260", "资质材料已过期");
            advanceFailCodeMap.put("236000000270", "所上传的资质材料与要求上传材料的名称不符");
            advanceFailCodeMap.put("236099999998", "");
        }
        return advanceFailCodeMap.get(status);
    }

    public CompanyMemInfoEsbService getCompanyMemInfoEsbService() {
        return companyMemInfoEsbService;
    }

    @EsbEIHttpWired
    public void setCompanyMemInfoEsbService(CompanyMemInfoEsbService companyMemInfoEsbService) {
        this.companyMemInfoEsbService = companyMemInfoEsbService;
    }

    public B2CAccountEsbService getB2CAccountEsbService() {
        return b2CAccountEsbService;
    }

    @EsbEIHttpWired
    public void setB2CAccountEsbService(B2CAccountEsbService b2cAccountEsbService) {
        b2CAccountEsbService = b2cAccountEsbService;
    }

    public MemberQueryService getMemberQueryService() {
        return memberQueryService;
    }

    @EsbEIHttpWired
    public void setMemberQueryService(MemberQueryService memberQueryService) {
        this.memberQueryService = memberQueryService;
    }
}
